package com.himooc.jdk8.lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

import com.himooc.jdk8.common.Gender;
import com.himooc.jdk8.common.Person;

/**
 * 测试stream
 * 
 * @author David Chen
 *
 */
public class TestStream {

	/**
	 * 获取用户列表
	 * 
	 * @return
	 */
	public static List<Person> getPersonList() {
		List<Person> personList = new ArrayList<>();
		Person person = new Person("张飞", 35, Gender.MALE, 1.83);
		personList.add(person);

		person = new Person("刘亦菲", 18, Gender.FEMALE, 1.7);
		personList.add(person);

		person = new Person("王菲", 38, Gender.FEMALE, 1.68);
		personList.add(person);

		return personList;
	}

	/**
	 * 测试流
	 */
	@Test
	public void testStream() {
		List<Person> personList = getPersonList();
		Stream<Person> personStream = personList.stream();

		personStream.forEach(person -> System.out.println(person.toString()));
	}

	/**
	 * 测试过滤器
	 */
	@Test
	public void testFilter() {
		List<Person> personList = getPersonList();
		Stream<Person> personStream = personList.stream();

		personStream.filter(p -> p.getGender() == Gender.FEMALE)
				.forEach(p -> System.out.println(p.toString()));
	}
	
	/**
	 * 测试DoubleStream
	 */
	@Test
	public void testDoubleStream() {
		double avgHeight = getPersonList().stream()
			.filter(p -> p.getName().indexOf("菲") >= 0)
			.mapToDouble(p -> p.getHeight())
			.average()
			.getAsDouble();
		
		System.out.println("名字中含有\"菲\"字的用户平均身高为： " + avgHeight + "米");
	}

}
